package writers_info.Task02;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import writers_info.JdbcUtils.JDBCUtils;
import writers_info.Writer;

import java.net.URL;
import java.util.List;

public class Task02 {
    public static void main(String[] args) throws Exception{
        JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
        String sql1 = "SELECT writer from writers where details is null;";
        String sql2 = "update writers set details=?, wurl=? where writer = ?";
        List<Writer> list = template.query(sql1, new BeanPropertyRowMapper<Writer>(Writer.class));
        list.remove("李白（存疑）");
        for (Writer writer : list) {
            try {
                String wurl = "https://baike.baidu.com/item/" + writer.getWriter();
                Document document = Jsoup.parse(new URL(wurl), 10000);
                Elements paras = document.select("div.lemma-summary > div.para");
                String details = "";
                for (Element para : paras) {
                    details += para.text();
                }
                writer.setDetails(details);
                writer.setWurl(wurl);
                System.out.println(writer.toString());//保存为空的多半是百度词条不存在
                template.update(sql2, details, wurl, writer.getWriter());
                System.out.println(writer.getWriter() + "已保存！");
            } catch (Exception e) {
                System.out.println(writer.getWriter() + "error!");
            }
        }
    }
}
